from PIL import Image, ImageDraw, ImageFont, ImageFilter,ImageEnhance
import random
from io import BytesIO
import base64
import os
from app.setting import APP_URL
import time
ImgCodePath = os.path.join(APP_URL.get("static_folder"), 'image')
FontPath = os.path.join(APP_URL.get("static_folder"), 'font')
def TextCode(n):
    #  *n代表生成几个随机字，与下面生成字符的n对应
    width = 60 * n
    height = 60
    #  生成图片
    image = Image.new('RGB', (width, height), (255, 255, 255))
    # 创建Font对象:
    font = ImageFont.truetype(FontPath + '/zi.ttf', 45)
    # 创建Draw对象:
    draw = ImageDraw.Draw(image)
    # 填充每个像素:
    for x in range(width):
        for y in range(height):
            draw.point((x, y), fill=(random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)))
    # 输出文字:
    listChar = []
    for t in range(6):
        # 生成文字
        char = chr(random.randint(65, 90))
        listChar.append(char)
        draw.text((60 * t + 10, 10), char, font=font,
                  fill=(random.randint(64, 90), random.randint(64, 90), random.randint(64, 90)))
    # 模糊:
    # image = image.filter(ImageFilter.BLUR)
    byIO = BytesIO()
    image.save(byIO, 'png')
    data = byIO.getvalue()
    data = u'data:image/png;base64,' + base64.b64encode(data).decode()
    return "".join(listChar), data


def SmsCode(phone):
    code = "6666"
    # for t in range(4):
    #     # 生成文字
    #     char = str(random.randint(0,9))
    #     code += char

    return {"code":code,"phone":phone,"time":int(time.time())}


class ImgCode():
    def __init__(self):
        pass
    def create(self):
        try:
            imglist = [
                '/imgcode1.jpg',
                '/imgcode2.jpg',
            ]

            # 随机获得列表中的一张图片
            image = Image.open(ImgCodePath + random.choice(imglist))
            # 将图片大小改为 300，150
            image = image.resize((300, 150), Image.ANTIALIAS)

            width, height = image.size

            image = image.convert('RGB')
            image = ImageEnhance.Sharpness(image).enhance(3.0)
            draw = ImageDraw.Draw(image)

            x = int((width - 80) / 4)
            y = height - 80
            codelist = []
            for i in range(4):
                text = self.GBK2312()
                tsize = random.randint(35, 45)
                setFont = ImageFont.truetype(FontPath + '/zi.ttf', tsize)
                strx = 40 + (x * i)
                stry = random.randint(40, y)
                self.text_border(draw, text, strx, stry, setFont, self.randomColor(), fillcolor=(0, 0, 0))

                session = {
                    'text': text,
                    'x1': strx,
                    'y1': stry,
                    'x2': strx + tsize,
                    'y2': stry + tsize
                }
                codelist.append(session)
            binary = BytesIO()
            # image.show()
            image.save(binary, 'png')
            data = binary.getvalue()
            data = u'data:image/png;base64,' + base64.b64encode(data).decode()
            random.shuffle(codelist)
            return {"session": codelist, "data": data}
        except:
            return False

    def GBK2312(self):
        head = random.randint(0xb0, 0xf7)
        body = random.randint(0xa1, 0xfe)
        val = f'{head:x} {body:x}'
        str = bytes.fromhex(val).decode('gb2312')
        return str

    def randomColor(self):
        # 随机生成3个64-255 数字的颜色
        return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
        # return (18,17,33)

    def text_border(self,draw, text, x, y, font, shadowcolor, fillcolor):
        # thin border
        draw.text((x - 1, y), text, font=font, fill=shadowcolor)
        draw.text((x + 1, y), text, font=font, fill=shadowcolor)
        draw.text((x, y - 1), text, font=font, fill=shadowcolor)
        draw.text((x, y + 1), text, font=font, fill=shadowcolor)

       # thicker border
        draw.text((x - 1, y - 1), text, font=font, fill=shadowcolor)
        draw.text((x + 1, y - 1), text, font=font, fill=shadowcolor)
        draw.text((x - 1, y + 1), text, font=font, fill=shadowcolor)
        draw.text((x + 1, y + 1), text, font=font, fill=shadowcolor)

        # now draw the text over it
        draw.text((x, y), text, font=font, fill=fillcolor)

